package com.llkj.qingnianguoxue.zhuanlan;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.ZhiBoAdapter;
import com.llkj.qingnianguoxue.base.BaseFragment;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.ResponseBean;
import com.llkj.qingnianguoxue.bean.ZhiBoListBean;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.login.LoginActivity;
import com.llkj.qingnianguoxue.util.ClickViewCallback;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.llkj.qingnianguoxue.util.helper.LoadDataHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * 直播
 */
public class ZhuanLanFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener,
        LoadDataHelper.LoadMoreListener, SwipeRefreshLayout.OnRefreshListener, ClickViewCallback {
    private static final int REQUEST_LOGIN_CODE = 9934;
    private static final int REQUEST_BOOK_CODE = 6789;
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView lvZhiBo;
    private ZhiBoAdapter zhiBoAdapter;//适配器
    private List<ZhiBoListBean.ZhiBoBean> zhiboData;//直播列表
    private int totalSize,mPage,mCurrentPosition;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_zhuanlan, container, false);
        setTitle("范儿直播", false, -1, -1, false, -1, -1);
        rlTitle.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorFE4A49));
        tvTitle.setTextColor(ContextCompat.getColor(getActivity(), R.color.white));

        initView();
        initListener();

//        onRefresh();
        return rootView;
    }

    private void initView() {
        refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.refresh_layout);
        refreshLayout.setColorSchemeResources(R.color.blue3989ff);
        lvZhiBo = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        lvZhiBo.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));

        zhiboData = new ArrayList<>();
        zhiBoAdapter = new ZhiBoAdapter(R.layout.item_zhibo, zhiboData, this);
        lvZhiBo.setAdapter(zhiBoAdapter);
    }

    private void initListener() {
        refreshLayout.setOnRefreshListener(this);
        zhiBoAdapter.setOnLoadMoreListener(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == REQUEST_BOOK_CODE) {

            }
        }else if(resultCode == getActivity().RESULT_OK && requestCode == REQUEST_LOGIN_CODE){
            onRefresh();
        }
    }

    @Override
    public void onLoadMore() {
        mPage++;
        getData();
    }

    @Override
    public void onRefresh() {
        mPage = 1;
        getData();
    }

    @Override
    public void onLoadMoreRequested() {
        LoadDataHelper.loadMoreRequest(this, zhiBoAdapter, null, lvZhiBo, totalSize);
    }

    @Override
    protected void dialogRightBtn() {
        super.dialogRightBtn();
        startActivityForResult(LoginActivity.class, new Bundle(),REQUEST_LOGIN_CODE);
    }

    @Override
    public void clickViewCallback(int position, int type, View view) {
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        if (!isLogin) {
            dialogConfirm(null, null, null, null).show();
            return;
        }
        mCurrentPosition = position;
        ZhiBoListBean.ZhiBoBean item = zhiboData.get(position);

        if(position==1){
            Bundle bundle = new Bundle();
            bundle.putString("id",item.getId());
            startActivityForResult(BookZhiBoActivity.class, bundle, REQUEST_BOOK_CODE);
            return;
        }
        switch (type) {
            case 0://预约直播
                loadWaitDialog();
                HttpMethod.liveOrder(getActivity(), this, item.getId());
                break;
            case 1://直播详情
                type = Integer.parseInt(item.getState());// 状态1 直播中 2 未开始 3 已结束

                Bundle bundle = new Bundle();
                bundle.putString("id",item.getId());
                switch (type) {
                    case 2://预约直播
                        startActivityForResult(BookZhiBoActivity.class, bundle, REQUEST_BOOK_CODE);
                        break;
                    case 1://正在直播
                        bundle.putString("type", "1");
                        startActivity(ZhiBoDetailActivity.class, bundle);
                        break;
                    case 3://直播回看
                        bundle.putString("type", "2");
                        startActivity(ZhiBoDetailActivity.class, bundle);
                        break;
                }
                break;
        }
    }

    private void getData(){
        if(mPage==1){
            try {
                handler.removeCallbacks(runnable);
            } catch (Exception e) {
                e.printStackTrace();
            }
            loadWaitDialog();
        }
        HttpMethod.liveIndex(getActivity(),this, String.valueOf(mPage));
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if(method == HttpMethod.HTTP_LIVE_INDEX){//7.1 直播首页
            ZhiBoListBean zhiBoListBean = GsonUtil.GsonToBean(data, ZhiBoListBean.class);
            if(zhiBoListBean != null){
                totalSize = Integer.parseInt(zhiBoListBean.getNum());
                if (mPage == 1) {
                    zhiBoAdapter.getCountDownList().clear();
                    zhiboData.clear();
                    LoadDataHelper.refreshComplete(zhiBoAdapter, zhiboData, refreshLayout, lvZhiBo);
                } else {
                    zhiBoAdapter.setEnableLoadMore(true);
                    zhiBoAdapter.loadMoreComplete();
                }
                zhiboData.addAll(zhiBoListBean.getList());
                zhiBoAdapter.notifyDataSetChanged();

                handler.postDelayed(runnable, 1000);
            }
        }else if(method == HttpMethod.HTTP_LIVE_ORDER){//7.2直播预约
            ToastUtil.makeLongText(getActivity(), "预约成功");
            ResponseBean responseBean = GsonUtil.GsonToBean(data,ResponseBean.class);
            if(responseBean != null){
                String time = responseBean.getResidue_time();
                ZhiBoListBean.ZhiBoBean item = zhiboData.get(mCurrentPosition);
                item.setIs_order("1");
                item.setCountdown(time);
                zhiBoAdapter.notifyItemChanged(mCurrentPosition);
            }
        }
    }

    @Override
    protected void onhttpFailed(String message, int method) {
        super.onhttpFailed(message, method);
        if(!StringUtils.isEmpty(message)){
            ToastUtil.makeLongText(getActivity(), message);
        }
    }

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            ZhiBoListBean.ZhiBoBean item = null;
            for(int i=0;i<zhiboData.size();i++){
                item = zhiboData.get(i);
                if("1".equals(item.getIs_order())){
//                    zhiBoAdapter.notifyItemChanged(i);
                    try {
                        String time = zhiBoAdapter.calculateTime(i,item);
                        zhiBoAdapter.getCountDownList().get(i).setText(time);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            handler.postDelayed(this, 1000);
        }
    };

}
